﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace AttachPropertyDemo
{
    public class PasswordEx : UIElement
    {
        public static string GetMyPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(MyPasswordProperty);
        }

        public static void SetMyPassword(DependencyObject obj, string value)
        {
            obj.SetValue(MyPasswordProperty, value);
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPasswordProperty =
            DependencyProperty.RegisterAttached("MyPassword", typeof(string), typeof(PasswordEx), new PropertyMetadata("", OnMyPasswordChanged));

        private static void OnMyPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = d as PasswordBox;
            if (passwordBox != null)
            {
                passwordBox.Password = e.NewValue.ToString();
            }
        }




        public static bool GetIsOpen(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsOpenProperty);
        }

        public static void SetIsOpen(DependencyObject obj, bool value)
        {
            obj.SetValue(IsOpenProperty, value);
        }

        // Using a DependencyProperty as the backing store for IsOpen.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsOpenProperty =
            DependencyProperty.RegisterAttached("IsOpen", typeof(bool), typeof(PasswordEx), new PropertyMetadata(true, OnIsOpenChanged));

        private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = d as PasswordBox;
            if (passwordBox != null)
            {
                passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
                passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
            }
        }

        private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox; 
            if (passwordBox != null)
            {
                SetMyPassword(passwordBox, passwordBox.Password);
                Console.WriteLine("Password changed: " + passwordBox.Password);
            }
        }
    }
}
